<?php

/**
 * test actions.
 *
 * @package    LIAnnot
 * @subpackage test
 * @author     Cedric Richier
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class testActions extends sfActions
{
	/**
	 * Executes index action
	 *
	 * @param sfRequest $request A request object
	 */
	public function executeIndex(sfWebRequest $request)
	{
		$this->annoset = Doctrine::getTable('Annoset')->find(18);;
		$this->marks = $this->annoset->getMarks();
		$this->structs = $this->annoset->getStructs();
		$this->feats_list = $this->annoset->getFeatsListTest();
		$this->rels = array();
		$this->entities = array();
		foreach($this->marks as $mark){
			$entity = array('table' => 'Mark', 'element' => $mark);
			$this->entities[$mark->getAttId()] = $entity;
		}
		foreach($this->structs as $struct){
			$entity = array('table' => 'Struct', 'element' => $struct);
			$this->entities[$struct->getAttId()] = $entity;
			$struct_rels = $struct->getRels();
			if(!$struct_rels)
			$struct_rels = null;
			$this->rels[$struct->getAttId()] = $struct_rels;
		}
	}

	public function executeExportMedia(sfWebRequest $request)
	{
		$luna_file = new DOMDocument('1.0', 'UTF-8');
		$luna_file->formatOutput = true;
		/********************/
		/*   CORPUS         */
		/********************/
		$corpus = $luna_file->createElement('corpus');
		$luna_file->appendChild($corpus);
		$this->annoset = Doctrine::getTable("annoset")->find(2);
		$id_annoset = $this->annoset->getId();
		$feats_list = $this->annoset->getFeatsListTest();
		print_r($feats_list);
		$corpus_name = mb_split('\.',$this->annoset->getName());
		$corpus_name = $corpus_name[0];
		$corpus->setAttribute('name', $corpus_name);
		$trans = "";
		$id_base = "";
		$href = "";
		$attvalues = Doctrine::getTable('mark')->createQuery('at')
				->where('at.id_annoset = ?', $id_annoset)
				->addWhere('at.list_type = ?', 'att')->execute();
		$frames = Doctrine::getTable('struct')->createQuery('f')
				->where('f.id_annoset = ?', $id_annoset)
				->addWhere('f.list_type =? ', 'frame')->execute();
		
		/********************/
		/*      TURNS       */
		/********************/
		$turns = Doctrine::getTable("mark")->findByIdAnnosetAndListType($id_annoset, "turn");

		/*foreach turns as turn*/
		$turnTest = $turns[0];
		$turn_xml = $luna_file->createElement('turn');
		$corpus->appendChild($turn_xml);
		$id_base = $turnTest->getAttId();
		$id_base = mb_substr($id_base, 5, mb_strlen($id_base, 'utf-8'), 'utf-8');
		$turn_xml->setAttribute('id', $id_base);
		$trans_xml = $luna_file->createElement('trans');
		$turn_xml->appendChild($trans_xml);
		$count = 0;
		$href = $turnTest->getHref();
		$hrefTab = Paula::XlinkToArray($href);
		$att_ids_list = array();
		/**********************/
		/*       TOKENS       */
		/**********************/
		$tokens = Doctrine::getTable('mark')->createQuery('m')->where('m.id_annoset = ?', $id_annoset)
		->addWhere('m.list_type = ?', 'tok')->andWhereIn('m.att_id', $hrefTab)->execute();
		$tokens_xml = $luna_file->createElement('tokens');
		$turn_xml->appendChild($tokens_xml);
		$tokens_tab = array();
		foreach($tokens as $token){
			$token_xml = $luna_file->createElement('token');
			$tokens_xml->appendChild($token_xml);
			$text = $token->getText();
			$tokens_tab[$token->getAttId()]['text'] = $text;
			$tok_id = $id_base.'_'.$count;
			$tokens_tab[$token->getAttId()]['id'] = $tok_id;
			array_push($att_ids_list, $token->getAttId());
			$token_xml->setAttribute('id', $tok_id);
			$token_xml->setAttribute('type', 'wtoken');
			$token_text = $luna_file->createTextNode($text);
			$token_xml->appendChild($token_text);
			$count++;
			$trans .= $text;
		}
		$trans_text = $luna_file->createTextNode($trans);
		$trans_xml->appendChild($trans_text);
		$tokens_xml->setAttribute('nb', $count);
		/************************/
		/*      ATTVALUES       */
		/************************/
		$count = 0;
		$attvalues_xml = $luna_file->createElement('attvalues');
		$turn_xml->appendChild($attvalues_xml);
		$attvalues_tab = array();
		foreach($attvalues as $attvalue){
			if($attvalue->isFather($att_ids_list)){
				array_push($att_ids_list, $attvalue->getAttId());
				$sons = Paula::XlinkToArray($attvalue->getHref());
				$att_xml = $luna_file->createElement('attvalue');
				$attvalues_xml->appendChild($att_xml);
				$attvalue_id = $id_base.'_50'.$count;
				$att_xml->setAttribute('id', $attvalue_id);
				$attvalue_tab[$attvalue->getAttId()]['id'] = $attvalue_id;
				$count++;
				$feats = $attvalue->getFeats();
				foreach($feats_list[$attvalue->getPaulaId()][$attvalue->getAttId()] as $name=>$value){
					$att_xml->setAttribute($name, $value);
				}
				$span = '';
				$first = true;
				$text = '';
				foreach($sons as $son){
					if($first === true){
						$first = false;
						$span .= $tokens_tab[$son]['id'];
					}
					else
					$span .= ' '.$tokens_tab[$son]['id'];
					$text .= $tokens_tab[$son]['text'];
				}
				$att_xml->setAttribute('span', $span);
				$att_text = $luna_file->createTextNode($text);
				$att_xml->appendChild($att_text);
			}
		}
		$attvalues_xml->setAttribute('nb', $count);
		/*****************************/
		/*         FRAMES            */
		/*****************************/
		
		$luna_file->save('uploads/projects/test.xml');//*/
		return sfView::NONE;
	}

	public function executeTestRel(sfWebRequest $request)
	{
		$annoset = Doctrine::getTable('Annoset')->find(28);
		$id_annoset = $annoset->getId();
		$table = 'Mark';
		$type = 'att';
		$this->test = Doctrine::getTable($table)->findOneByIdAnnosetAndListType($id_annoset, $type);
		$this->list = $featsLists;
	}

	private function feedListByElementType(&$featsLists, $elements, $id, $table){
		$typeArray = array();
		$nameArray = array();
		foreach($elements as $element){
			$type = $element->getListType();
			if($type == 'annoSet')
			continue;
			$pattern = '%'.$element->getAttId().'%';
			$feats = Doctrine::getTable('Feat')->createQuery('f')->where('f.id_annoset = ?', $id)
			->addWhere('f.href LIKE ?', $pattern)->execute();
			if(!in_array($type, $typeArray)){
				$featsLists[$type] = array();
				$featsLists[$type]['table'] = $table;
				$featsLists[$type]['list'] = array();
				$nameArray[$type] = array();
				$typeArray[] = $type;
			}
			foreach($feats as $feat){
				$name = $feat->getName();
				$paula_id = $feat->getPaulaId();
				if($name === null){
					$name = $feat->getListType();
				}
				if(!in_array($name, $nameArray[$type])){
					$nameArray[$type][] = $name;
					$featsLists[$type]['list'][$name] = array('values'=> array(),
							'paula_id'=>$paula_id);
				}
				$value = $feat->getValue();
				if(!in_array($value, $featsLists[$type]['list'][$name]['values']))
				array_push($featsLists[$type]['list'][$name]['values'], $value);
			}
		}
	}

	public function executeHideLayer(sfWebRequest $request)
	{
		$idAnnoset = $request->getParameter('annoset');
		$layer = $request->getParameter('layer');
		$table = $request->getParameter('table');
		$elements_to_hide = Doctrine::getTable($table)->createQuery('q')->select('q.att_id')
		->where('q.list_type = ?', $layer)->addWhere('q.id_annoset = ?', $idAnnoset)->execute();
		$this->ids_to_hide = array();
		foreach($elements_to_hide as $element){
			$this->ids_to_hide[] = $element->getAttId();
		}
		echo json_encode($this->ids_to_hide);
		return sfView::NONE;
	}


	public function executeFeatsTest(sfWebRequest $request)
	{
		$this->annoset = Doctrine::getTable('Annoset')->find("2");
		$id = $this->annoset->getId();
		$this->delimitersList = MarkTable::queryWithDistinctListType($id)->execute()->toArray();

		if($request->getParameter('delimiter'))
		$this->delimiter = $request->getParameter("delimiter");
		else
		$this->delimiter = "#";
		/*******************************test layers to hide************************************/
		$markLayers = Doctrine::getTable('Mark')->createQuery('m')->select('m.list_type')
		->where('m.id_annoset = ?', $id)->groupBy('m.list_type ASC')
		->execute()->toArray();
		// ->having('m.list_type != ?', $this->delimiter) avoid delimiter to be part of layers to hide
		$this->layers = array();
		$this->layers['Mark'] = array();
		foreach($markLayers as $layer){
			$this->layers['Mark'][] = $layer;
		}
		$stuctLayers = Doctrine::getTable('Struct')->createQuery('s')->select('s.list_type')
		->where('s.id_annoset = ?', $id)->groupBy('s.list_type')->having('s.list_type != ?', 'annoSet')
		->execute()->toArray();
		$this->layers['Struct'] = array();
		foreach($stuctLayers as $layer){
			$this->layers['Struct'][] = $layer;
		}
		/****************************************/
		$this->delimitersIds = array();
		$this->delimiters = MarkTable::queryWithDelimiter($this->annoset->getId(), $this->delimiter)->execute();
		$this->index = 1;
		$this->action = '';
		if($request->getParameter('index'))
		$this->index = $request->getParameter('index');
		if($request->getParameter('action'))
		$this->action = $request->getParameter('action');
		$this->total = ($this->delimiters->count() != 0)? $this->delimiters->count() : 1;
		$this->tokens_by_dlmt = array();
		foreach($this->delimiters as $dlmt)
		{
			$this->delimitersIds[] = $dlmt->getAttId();
			if($this->delimiter != 'tok'){
				$href = Paula::XlinkToArray($dlmt->getHref());
				$this->tokens_by_dlmt[] = $href;
			}
			else
			$this->tokens_by_dlmt[] = $dlmt->getAttId();
		}
		if($this->delimiter != "#"){
			$this->tokens = Doctrine::getTable('Mark')->createQuery('m')
			->whereIn('m.att_id', $this->tokens_by_dlmt[$this->index - 1])->addWhere('m.list_type = ?', 'tok')
			->addWhere('m.id_annoset = ?', $id)->execute();
		}
		else{
			$this->tokens = Doctrine::getTable('Mark')->createQuery('m')
			->where('m.list_type = ?', 'tok')
			->addWhere('m.id_annoset = ?', $id)->execute();
			$this->delimitersIds[0] = ""; //to hack offset pb
		}

		$this->att_ids_list = array();
		foreach($this->tokens as $token){
			array_push($this->att_ids_list, $token->getAttId());
		}

		/***********************************************************************************************************/



		$this->marks = MarkTable::queryWithOutDelimiter($this->annoset->getId(), $this->delimiter)->execute();
		$this->structs = StructTable::queryWithRelsByIdAnnoset($this->annoset->getId())->execute();
		$this->feats_list = $this->annoset->getFeatsListTest();
		$rels = array();
		$entities = array();
		foreach($this->delimiters as $delimiter){
			$entity = array('table' => 'Mark', 'element' => $delimiter);
			$entities[$delimiter->getAttId()] = $entity;
		}

		foreach($this->marks as $mark){
			$entity = array('table' => 'Mark', 'element' => $mark);
			$entities[$mark->getAttId()] = $entity;
		}

		foreach($this->structs as $struct){
			$entity = array('table' => 'Struct', 'element' => $struct);
			$entities[$struct->getAttId()] = $entity;
			$struct_rels = $struct->getRels();
			if(!$struct_rels)
			$struct_rels = null;
			$rels[$struct->getAttId()] = $struct_rels;
		}


		$this->all_marks_level = array();
		$this->all_structs_level = array();
		$this->marks_level = array();
		$this->structs_level = array();
		$this->max_level = 0;

		foreach($this->marks as $mark):
		$element = Paula::getLevelTest($mark, $entities, $rels);
		$level = $element['level'];
		if($level > $this->max_level)
		$this->max_level = $level;
		$this->all_marks_level[$level][] = $element;
		endforeach;

		ksort($this->all_marks_level);


		foreach($this->structs as $struct):
		if($struct->getListType() != 'annoSet'):
		$element = Paula::getLevelTest($struct, $entities, $rels);
		$level = $element['level'];
		if($level > $this->max_level)
		$this->max_level = $level;
		$this->all_structs_level[$level][] = $element;
		endif;
		endforeach;
			
		ksort($this->all_structs_level);
			
			
		foreach($this->all_marks_level as $level=>$entities){
			if($level == 0){
				foreach($entities as $entity){
					if(in_array($entity['element']->getAttId(), $this->att_ids_list))
					$this->marks_level[$level][] = $entity;
				}
			}
			else{
				foreach($entities as $entity){
					foreach($entity['sons'] as $son){
						if(in_array($son['son']->getAttId(), $this->att_ids_list)){

							array_push($this->att_ids_list, $entity['element']->getAttId());
							$this->marks_level[$level][] = $entity;
							break;
						}
					}
				}
			}
		}
			
		foreach($this->all_structs_level as $level=>$entities){
			if($level == 0){
				$this->structs_level[$level] = $entities;
			}
			else{
				foreach($entities as $entity){
					foreach($entity['sons'] as $son){
						if(in_array($son['son']->getAttId(), $this->att_ids_list)||
						$son['son']->getAttId() == $this->delimitersIds[$this->index -1]){
							array_push($this->att_ids_list, $entity['element']->getAttId());
							$this->structs_level[$level][] = $entity;
							break;
						}
					}
				}
			}
		}
			
		ksort($this->marks_level);
		ksort($this->structs_level);
	}


	public function executePaulaTest()
	{
		Paula::saveInBd('LUNA_TEST.1016');
		/*$annoset = Doctrine::getTable('Annoset')->find('7');
		 $annoset->delete();//*/
	}

	public function executeDeletePaulaTest()
	{
		$this->annoset = Doctrine::getTable('Annoset')->findOneByName('LUNA_DEV_CRICRI.13');
		$this->annoset->delete();
	}

	public function executeTests()
	{
		$this->annoset = Doctrine::getTable('Annoset')->find(21);
		$this->delimiter = "turn";
		$this->marks = MarkTable::queryWithOutDelimiter($this->annoset->getId(), $this->delimiter)
		->execute();
		$this->structs = StructTable::queryWithRelsByIdAnnoset($this->annoset->getId())->execute();
		$this->feats_list = $this->annoset->getFeatsListTest();
		$rels = array();
		$entities = array();

		foreach($this->marks as $mark){
			$entity = array('table' => 'Mark', 'element' => $mark);
			$entities[$mark->getAttId()] = $entity;
		}

		foreach($this->structs as $struct){
			$entity = array('table' => 'Struct', 'element' => $struct);
			$entities[$struct->getAttId()] = $entity;
			$struct_rels = $struct->getRels();
			if(!$struct_rels)
			$struct_rels = null;
			$rels[$struct->getAttId()] = $struct_rels;
		}

		/******************************************************/

		$this->marks_level = array();
		$this->structs_level = array();
		$this->max_level = 0;

		foreach($this->marks as $mark):
		$element = Paula::getLevelTest($mark, $entities, $rels);
		$level = $element['level'];
		if($level > $this->max_level)
		$this->max_level = $level;
		$this->marks_level[$level][] = $element;
		endforeach;

		ksort($this->marks_level);


		foreach($this->structs as $struct):
		if($struct->getListType() != 'annoSet'):
		$element = Paula::getLevelTest($struct, $entities, $rels);
		$level = $element['level'];
		if($level > $this->max_level)
		$this->max_level = $level;
		$this->structs_level[$level][] = $element;
		endif;
		endforeach;
			
		ksort($this->structs_level);
			
		/****************************************************/
			
	}

	public function executeSetFeats(sfWebRequest $request){
		$id_annoset = $request->getParameter('annoset');
		$annoset = Doctrine::getTable('Annoset')->find($id_annoset);
		$elementId = $request->getParameter('elementId');
		$json = $request->getParameter('json');
		$newFeats = json_decode($json, true);
		$paula_id = $request->getParameter('paula_id');
		$elementFile = Doctrine::getTable('File')->findOneByIdAnnosetAndPaulaId($id_annoset,
		$paula_id);
		$elementFileName = $elementFile->getName();
		$projectName = $annoset->getName();
		foreach($newFeats as $name=>$feat){
			if(!$feat['paula_id'])
			echo 'paula_id : NULL<br/>';
			/*
			 * TODO create new file?
			 */
			else{
				$featFile = Doctrine::getTable('File')->findOneByIdAnnosetAndPaulaId($id_annoset,
				$feat['paula_id']);
				$this->addFeat($projectName, $featFile->getName(),
				$name, $feat['value'], $elementId, $elementFileName, $id_annoset);
			}
		}

		/*$elementFile = Doctrine::getTable('File')->findOneByIdAnnosetAndPaulaId($id, $paula_id);
		 $elementRel = Doctrine::getTable('Rel')->findOneByHref($elementFile->getName());
		 $idStruct = $elementRel->getIdStruct();
		 $rels = Doctrine::getTable('Rel')->createQuery('r')->leftJoin('r.Struct s')
		 ->where('r.id_struct = ?', $idStruct)
		 ->addWhere('s.id_annoset = ?', $id)
		 ->addWhere('r.href != ?', $elementFile->getName())
		 ->addWhere('substring(r.href, 1, 1) != ?', '#')->execute();
		 $filesNames = array();
		 foreach($rels as $rel){
			array_push($filesNames, $rel->getHref());
			}
			$featsFiles = Doctrine::getTable('File')->createQuery('f')
			->whereIn('f.name', $filesNames)
			->addWhere('f.id_annoset = ?', $id)
			->addWhere('f.type =?', 'Feat')->execute();
			$paulaIds = array();
			foreach($featsFiles as $featsFile){
			array_push($paulaIds, $featsFile->getPaulaId());
			}
			$feats = Doctrine::getTable('Feat')->createQuery('f')
			->whereIn('f.paula_id', $paulaIds)
			->whereIn('f.base', array(null, $elementFile->getName()))
			->addWhere('f.id_annoset = ?', $id)->execute();
			print_r($feats->toArray());//*/
		return sfView::NONE;
	}

	private function addFeat($projectName, $file_name, $name, $value, $elementId,
	$elementFileName, $id_annoset){
		$doc = new DOMDocument();
		$doc->formatOutput = true;
		$doc->preserveWhiteSpace = false;
		if(!$doc->load("uploads/projects/".$projectName."/".$file_name))
		return false;
		$paula = $doc->documentElement;
		$header = $paula->firstChild;
		$parentNode = $paula->firstChild->nextSibling;
		$prefix = ($parentNode->hasAttribute('xml:base'))? "" : $elementFileName;
		$base = ($parentNode->hasAttribute('xml:base'))? $elementFileName : null;
		$featElement = $doc->createElement('feat');
		$featDB = new Feat();
		$featDB->setIdAnnoset($id_annoset);
		$featDB->setPaulaId($header->getAttribute('paula_id'));
		if($base){
			$featDB->setBase($base);
		}
		$featDB->setListType($parentNode->getAttribute('type'));
		switch($parentNode->nodeName){
			case 'multiFeatList':
				$nodeList = $parentNode->getElementsByTagName('multiFeat');
				$isReferenced = false;
				foreach($nodeList as $node){
					if(preg_match('/'.$elementId.'/', $node->getAttribute('xlink:href')) != 0){
						$parentNode = $node;
						$isReferenced = true;
						break;
					}
				}
				if(!$isReferenced){
					$element = $doc->createElement('multiFeat');
					$multiFeat = $parentNode->appendChild($element);
					$multiFeat->setAttribute('xlink:href', $prefix.'#'.$elementId);
					$parentNode = $multiFeat;
				}
				$featDB->setHref($parentNode->getAttribute('xlink:href'));
				$feat = $parentNode->appendChild($featElement);
				$feat->setAttribute('name', $name);
				$featDB->setName($name);
				break;
			case 'featList':
				$feat = $parentNode->appendChild($featElement);
				$feat->setAttribute('xlink:href', $prefix.'#'.$elementId);
				$featDB->setHref($feat->getAttribute('xlink:href'));
				break;
			default:
				break;
		}
		$feat->setAttribute('value', $value);
		$featDB->setValue($value);
		$featDB->save();
		$doc->save("uploads/projects/".$projectName."/".$file_name);
	}

	public function executeGetLayers(sfWebRequest $request){
		$id = $request->getParameter("annoset");
		$annoset = Doctrine::getTable("annoset")->find($id);
		$marks = $annoset->getMarks();
		$featsLists = array();
		$this->feedListByElementType($featsLists, $marks, $id, 'Mark');
		$structs = $annoset->getStructs();
		$this->feedListByElementType($featsLists, $structs, $id, 'Struct');
		ksort($featsLists);
		foreach($featsLists as $type=>$featsList){
			ksort($featsLists[$type]['list']);
			foreach($featsList['list'] as $name=>$feats){
				asort($featsLists[$type]['list'][$name]['values']);
			}
		}
		$json = json_encode($featsLists);
		$this->getResponse()->setHttpHeader('Content-type', 'application/json');
		//$this->getResponse()->setContent(json_encode($featsLists));
		return $this->renderText($json);
		//return sfView::NONE;
	}

	public function executeCreateElement(sfWebRequest $request){
		$id_annoset = $request->getParameter("annoset");
		$annoset = Doctrine::getTable("annoset")->find($id_annoset);
		$projectName = $annoset->getName();
		$table = $request->getParameter('table');
		$type = $request->getParameter('type');
		$test = Doctrine::getTable($table)
		->findOneByIdAnnosetAndListType($id_annoset, $type);
		$paula_id = $test->getPaulaId();
		$base = $test->getBase();
		$fileName = $test->getFile()->getName();
		if($table == 'Mark'){
			$element = new Mark();
			$element->setHref("");
		}
		elseif($table == 'Struct')
		$element = new Struct();
		$element->setIdAnnoset($id_annoset);
		$element->setPaulaId($paula_id);
		$element->setListType($type);
		if($base !== null)
		$element->setBase($base);
		$element->save();
		$id = $element->getId();
		$att_id = $type.'_'.$id;
		$element->setAttId($att_id);
		$element->save();
		$this->createInFile($fileName, $att_id, $table, $projectName);
		echo json_encode(array('paula_type'=>$type, 'paula_id'=>$paula_id,
				'elementId'=>$id));
		return sfView::NONE;
	}


	/*****************************************************/

	/*
	 * function ok, but not optimized
	 */
	public function executeDeleteElement(sfWebRequest $request){
		$idAnnoset = $request->getParameter('annoset');
		$annoset = Doctrine::getTable('annoset')->find($idAnnoset);
		$annosetName = $annoset->getName();
		$att_id = $request->getParameter('att_id');
		$list_type = $request->getParameter('list_type');
		$paula_id = $request->getParameter('paula_id');
		$file = Doctrine::getTable('File')->createQuery('f')->select('f.name, f.type')
		->where('f.id_annoset = ?', $idAnnoset)->addWhere('f.paula_id = ?', $paula_id)->execute();
		$tableOfElement = $file[0]->getType();
		$element_to_delete = Doctrine::getTable($tableOfElement)->findOneByAttIdAndIdAnnoset($att_id, $idAnnoset);
		$pattern = '%'.$att_id.'%';
		$structs =StructTable::queryWithRelsByIdAnnoset($idAnnoset)
		->addWhere('r.href LIKE ?', $pattern)->execute();
		/**************Structs******************/
		foreach($structs as $struct){
			$rels = $struct->getRels();
			$structFile = $struct->getFile();
			foreach($rels as $rel){
				/*TODO
				 * check href :
				 * if att_id is the only one linked, delete rel : first in files then in bdd (1)
				 * else update rel first in files then in bdd (2)
				 */
				//need function for checking href with att_id... a Paula one? -> currently a private method
				/********TEST*************/
				$href = $rel->getHref();
				if($this->checkHrefWithId($href, $att_id) == true){ // (1)
					$structFileName = $structFile->getName();
					$relId = $rel->getAttId();
					/*
					 * (a) delete in files...
					 * (b) find feats related to this rel then delete them (file + bdd)
					 * (c) delete in bdd...
					 */

					/*********(b)*********/
					$relPattern = '%'.$relId.'%';
					$feats = Doctrine::getTable('Feat')->createQuery('f')->select('f.*')
					->where('f.id_annoset = ?', $idAnnoset)->addWhere('f.href LIKE ?', $relPattern)
					->execute();
					foreach($feats as $feat){
						$featFile = Doctrine::getTable('File')->findOneByIdAnnosetAndPaulaId($idAnnoset, $feat->getPaulaId());
						$featFileName = $featFile->getName();
						$featHref = $feat->getHref();
						$this->deleteInFileByHref($featFileName, $featHref, $annosetName);
						$feat->delete();
					}
					/********end (b)*****/
					 	
					/********(a)***********/
					$this->deleteInFile($structFileName, $relId, 'rel', $annosetName);
					/********end (a)*******/
					 	
					/*********(c)**********/
					$rel->delete();
					/********end (c)*******/
				}
				else // (2)
				/*have to create a new href*/
				/*
				 * (a) update in files
				 * (b) update in bdd
				 */
				echo 'todo!\n';

				/********end TEST********/
			}
		}
		/*************end Structs********************/

		/*TODO
		 * check feats like structs
		 */
		/****************Feats*******************/

		$feats = Doctrine::getTable('Feat')->createQuery('f')->select('f.*')
		->where('f.id_annoset = ?', $idAnnoset)->addWhere('f.href LIKE ?', $pattern)->execute();
		foreach($feats as $feat){
			/*TODO
			 * check href:
			 * if att_id is the only one linked, delete feat : first in files, then in bdd
			 * else update feat first in files, then in bdd
			 */
			//need function for checking href with att_id... a Paula one?
			if($this->checkHrefWithId($feat->getHref(), $att_id) == true){
				$featFile = Doctrine::getTable('File')->findOneByIdAnnosetAndPaulaId($idAnnoset, $feat->getPaulaId());
				$featFileName = $featFile->getName();
				$featHref = $feat->getHref();
				$this->deleteInFileByHref($featFileName, $featHref, $annosetName);
				$feat->delete();
			}
		}

		/*****************endFeats***************/

		/*TODO
		 * delete element_to_delete first in files, then in bdd
		 * !!! Don't forget feats for links!!!! (if element is of type struct...)
		 */
		/*********element_to_delete************/
		/*first check type of element*/
		if($tableOfElement == 'Struct'){
			// if struct, delete feats for rels
			$rels = $element_to_delete->getRels();
			foreach($rels as $rel){
				$href = $rel->getHref();
				$relId = $rel->getAttId();
				$relPattern = '%'.$relId.'%';
				$feats = Doctrine::getTable('Feat')->createQuery('f')->select('f.*')
				->where('f.id_annoset = ?', $idAnnoset)->addWhere('f.href LIKE ?', $relPattern)
				->execute();
				foreach($feats as $feat){
					$featFile = Doctrine::getTable('File')->findOneByIdAnnosetAndPaulaId($idAnnoset, $feat->getPaulaId());
					$featFileName = $featFile->getName();
					$featHref = $feat->getHref();
					$this->deleteInFileByHref($featFileName, $featHref, $annosetName);
					$feat->delete();
				}
			}
		}

		/*then delete element in file*/
		$this->deleteInFile($file[0]->getName(), $att_id, strtolower($tableOfElement), $annosetName);
		/*finaly, delete element in bdd*/
		$element_to_delete->delete();
		/*********end_element_to_delete********/
		echo json_encode('success');
		return sfView::NONE;
	}

	public function executeDeleteStructLink(sfWebRequest $request){
		$idAnnoset = $request->getParameter('annoset');
		$annoset = Doctrine::getTable('annoset')->find($idAnnoset);
		$annosetName = $annoset->getName();
		$idRel = $request->getParameter('idRel');
		$rel_to_delete = Doctrine::getTable('Rel')->find($idRel);
		$struct = $rel_to_delete->getStruct();
		$file = $struct->getFile();
		$file_name = $file->getName();
		$pattern = '%'.$rel_to_delete->getAttId().'%';
		$feats = Doctrine::getTable('Feat')->createQuery('f')->select('f.*')
		->where('f.id_annoset = ?', $idAnnoset)
		->addWhere('f.href LIKE ?', $pattern)->execute();
		foreach($feats as $feat){
			$featFile = Doctrine::getTable('File')->findOneByIdAnnosetAndPaulaId($idAnnoset, $feat->getPaulaId());
			$featFileName = $featFile->getName();
			$featHref = $feat->getHref();
			$this->deleteInFileByHref($featFileName, $featHref, $annosetName);
			$feat->delete();
		}
		$this->deleteElementById($file_name, $rel_to_delete->getAttId(), $annosetName);
		$rel_to_delete->delete();
		echo json_encode("success");
		return sfView::NONE;
	}

	public function executeDeleteMarkLink(sfWebRequest $request){
		$idMark = $request->getParameter('elementId');
		$attIdDest = $request->getParameter('attIdDest');
		$mark = Doctrine::getTable('Mark')->find($idMark);
		$annosetName = $mark->getAnnoset()->getName();
		$file = $mark->getFile();
		$href = $mark->getHref();
		$tab = Paula::XlinkToArray($href);
		array_splice($tab, array_search($attIdDest, $tab), 1);
		$newHref = Paula::arrayToXlink($tab);
		//update in files
		$this->updateHrefInFile($file->getName(), 'mark', $href, $newHref, $annosetName);
		//update in db
		$mark->setHref($newHref);
		$mark->save();
		echo json_encode("success");
		return sfView::NONE;
	}

	public function executeAddLink(sfWebRequest $request){
		$response = "not yet implemented";
		$annoset_id = $request->getParameter('annoset_id');
		$elementFrom = json_decode($request->getParameter('from'), true);
		$elementTo = json_decode($request->getParameter('to'), true);
		$annoset = Doctrine::getTable('Annoset')->find($annoset_id);
		$project_name = $annoset->getName();
		try{
			if($elementFrom['paula_type'] == 'tok')
			throw new Exception();
			$fileFrom = Doctrine::getTable('File')
			->findOneByIdAnnosetAndPaulaId($annoset_id, $elementFrom['paula_id']);
			$fileTo = Doctrine::getTable('File')
			->findOneByIdAnnosetAndPaulaId($annoset_id, $elementTo['paula_id']);
			if($fileFrom->getType() == 'Struct'){
				$struct = Doctrine::getTable('Struct')->find($elementFrom['elementId']);
				$base = $struct->getBase();
				if($base){
					if($base != $fileTo->getName())
					throw new Exception();
				}
				$rel = new Rel();
				$rel->setIdStruct($elementFrom['elementId']);
				$prefix = '#';
				if(!$base)
				$prefix = $fileTo->getName().'#';
				$rel->setHref($prefix.$elementTo['attId']);
				$rel->save();
				$rel_attId = 'rel_'.$rel->getId();
				$rel->setAttId($rel_attId);
				$rel->save();
				//update in file
				$this->createRelInFile($fileFrom->getName(), $elementFrom['attId'],
				$project_name, $rel);
				//set response
				$response = $rel->getId();
			}
			elseif($fileFrom->getType() == 'Mark'){
				$mark = Doctrine::getTable('Mark')->find($elementFrom['elementId']);
				$href = $mark->getHref();
				$array = Paula::XlinkToArray($href);
				$newEntry = $elementTo['attId'];
				if(!$mark->getBase()){
					$prefix =$fileTo->getName();
					$newEntry = $prefix.'#'.$newEntry;
				}
				elseif($mark->getBase()!= $fileTo->getName())
				throw new Exception();
				array_push($array, $newEntry);
				$newHref = Paula::arrayToXlink($array);
				$mark->setHref($newHref);
				$mark->save();
				//update in file
				$this->updateHrefInFile($fileFrom->getName(), 'mark', $href, $newHref, $project_name);
				//set response
				$response = 'l';
			}
		} catch(Exception $e){
			$response = 'cannot link those elements';
		}
		return $this->renderText(json_encode($response));
	}

	private function checkHrefWithId($href, $att_id){
		$array = Paula::XlinkToArray($href);
		if(in_array($att_id, $array) && count($array) == 1)
		return true;
		else return false;
	}

	private function deleteInFile($fileName, $eltId, $type, $projectName){
		$doc = new DOMDocument();
		$doc->formatOutput = true;
		$doc->preserveWhiteSpace = false;
		if(!$doc->load("uploads/projects/".$projectName."/".$fileName))
		return false;
		$elements = $doc->getElementsByTagName($type);
		foreach($elements as $element){
			if($element->getAttribute('id') == $eltId){
				$element->parentNode->removeChild($element);
			}
		}
		$doc->save("uploads/projects/".$projectName."/".$fileName);
	}

	private function createInFile($fileName, $eltId, $type, $projectName){
		$doc = new DOMDocument();
		$doc->formatOutput = true;
		$doc->preserveWhiteSpace = false;
		if(!$doc->load("uploads/projects/".$projectName."/".$fileName))
		return false;
		$paula = $doc->documentElement;
		$parentNode = $paula->firstChild->nextSibling;
		$type = mb_strtolower($type, 'UTF-8');
		$element =$doc->createElement($type);
		$newNode = $parentNode->appendChild($element);
		$newNode->setAttribute("id", $eltId);
		if($type == 'mark'){
			$newNode->setAttribute("xlink:href", "");
		}
		$doc->save("uploads/projects/".$projectName."/".$fileName);
	}

	private function createRelInFile($fileName, $eltId, $projectName, $relDB){
		$doc = new DOMDocument();
		$doc->formatOutput = true;
		$doc->preserveWhiteSpace = false;
		if(!$doc->load("uploads/projects/".$projectName."/".$fileName))
		return false;
		$doc->validate();
		$element = $doc->getElementById($eltId);
		$newElement = $doc->createElement('rel');
		$rel = $element->appendChild($newElement);
		$rel->setAttribute('id', $relDB->getAttId());
		$rel->setAttribute('xlink:href', $relDB->getHref());
		if($relDB->getType())
		$rel->setAttribute('type', $relDB->getType());
		$doc->save("uploads/projects/".$projectName."/".$fileName);
	}

	private function deleteInFileByHref($fileName, $href, $projectName){
		$doc = new DOMDocument();
		$doc->formatOutput = true;
		$doc->preserveWhiteSpace = false;
		if(!$doc->load("uploads/projects/".$projectName."/".$fileName))
		return false;
		$paula = $doc->documentElement;
		$node = $paula->firstChild->nextSibling;
		if($node->nodeName == 'featList')
		$type = 'feat';
		else if($node->nodeName == 'multiFeatList')
		$type = 'multiFeat';
		$elements = $doc->getElementsByTagName($type);
		foreach($elements as $element){
			if($element->getAttribute('xlink:href') == $href){
				$element->parentNode->removeChild($element);
			}
		}
		$doc->save("uploads/projects/".$projectName."/".$fileName);
	}

	private function deleteElementById($fileName,  $id_element, $projectName){
		$doc = new DOMDocument();
		$doc->formatOutput = true;
		$doc->preserveWhiteSpace = false;
		if(!$doc->load("uploads/projects/".$projectName."/".$fileName))
		return false;
		$xpath = new DOMXPath($doc);
		$path = "//*[@id = '".$id_element."']";
		$element = $xpath->query($path)->item(0);
		$element->parentNode->removeChild($element);
		$doc->save("uploads/projects/".$projectName."/".$fileName);
	}

	private function updateHrefInFile($fileName, $type, $href, $newHref, $projectName){
		$doc = new DOMDocument();
		$doc->formatOutput = true;
		$doc->preserveWhiteSpace = false;
		if(!$doc->load("uploads/projects/".$projectName."/".$fileName))
		return false;
		$elements = $doc->getElementsByTagName($type);
		foreach($elements as $element){
			if($element->getAttribute('xlink:href') == $href)
			$element->setAttribute("xlink:href", $newHref);
		}
		$doc->save("uploads/projects/".$projectName."/".$fileName);
	}

}
